<?php

namespace app\common\model\merchant;

use app\common\model\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

/**
 * 商户基本信息
 * Class MerchantInfo
 * @package app\common\model\merchant
 */
class MerchantInfoModel extends BaseModel
{
    //
    protected $name = 'merchant_info';

    // 商户ID
    public string $fieldMerId = 'mer_id';
    // 商户名称
    public string $fieldTitle = 'title';
    // 公司名称
    public string $fieldCompanyName = 'company_name';
    // 地址
    public string $fieldAddress = 'address';
    // 联系人
    public string $fieldContact = 'contact';
    // 导购入口
    public string $fieldEntry = 'entry';
    // 更新时间
    public string $fieldUpdateAt = 'update_at';
    // 手机号码
    public string $fieldMobile = 'mobile';
    // 商户状态 1:正常  0禁用
    public string $fieldStatus = 'status';
    // 关联管理员ID
    public string $fieldAssocManagerId = 'assoc_manager_id';

    // 设置字段信息
    protected $schema = [
        'mer_id' => 'string',        // 商户ID
        'title' => 'string',        // 商户名称
        'company_name' => 'string',        // 公司名称
        'address' => 'string',        // 地址
        'contact' => 'string',        // 联系人
        'entry' => 'string',        // 导购入口
        'update_at' => 'datetime',        // 更新时间
        'mobile' => 'string',        // 手机号码
        'status' => 'int',        // 商户状态 1:正常  0禁用
        'assoc_manager_id' => 'int',        // 关联管理员ID
    ];


    /**
     * 检测商户是不可用
     * @param string $mer_id 商户编号
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function checkMerchantStatus(string $mer_id): array
    {
        $info = $this->where('mer_id', $mer_id)->field('mer_id,company_name,phone,mobile,status,end_time')->find();

        if (empty($info) || $info['status'] !== 1 || $info['end_time'] < date('Y-m-d')) {
            return [];
        }
        return $info;
    }

    /**
     * 商户分页
     * @param array $wheres 条件
     * @param int $pageSize 页面大小
     * @return array
     * @throws DbException
     */
    public function pageList(array $wheres, int $pageSize): array
    {
        return $this->db()->alias('a')->join('merchant_stock b', 'a.mer_id=b.mer_id')
            ->where($wheres)
            ->field('a.mer_id,a.assoc_manager_id,company_name as title,address,contact,mobile,balance,virtual_num,real_num,a.update_at,status,end_time,round((extract(epoch from end_time) - extract(epoch from now())) / (60 * 60 * 24)) as diff_day,memo')
            ->order('mer_id desc')
            ->paginate($pageSize);
    }

    /**
     * 获取商户详情
     * @param string $mer_id 商户
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getInfo(string $mer_id)
    {
        return $this->db()->alias('a')->join('merchant_stock b', 'a.mer_id=b.mer_id')
            ->where('a.mer_id', $mer_id)
            ->field('a.mer_id,title,company_name,address,contact,mobile,balance,virtual_num,a.update_at,status,end_time')
            ->find();
    }

    /**
     * 获取商户详情
     * @param $where |条件
     * @param $field | 查询信息
     * @return mixed
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserInfo($where, $field)
    {
        $data = $this->db()->where($where)
            ->cache(true, MINUTES_SECOND_5)
            ->field($field)->find();
        if (empty($data)) {
            throw  new Exception('商户信息不存在或禁用');
        }
        return $data;
    }

    /**
     * 获取商户信息
     * @param string $mer_id 商户编号
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function getOpenidAndMobile(string $mer_id): array
    {

        $result = ['open_id' => '', 'mobile' => ''];
        $info = $this->db()->alias('a')->join('merchant b', 'a.assoc_manager_id=b.id')
            ->where('a.mer_id', $mer_id)->field('open_id,a.mobile')->find();
        return empty($info) ? $result : $info;
    }

    /**
     *  扫码提交异常抛出
     */
    public function throwErrorMerchant($mer_id, $err = API_EXCEPTION, $errMsg = '', $msg = [], $name = '导购')
    {
        $merchant = $this->db()->where('mer_id', $mer_id)->cache(true, HOUR_SECOND)->find();
        api_result($err, $errMsg, [
            'msg' => $msg,
            'name' => $name ?? '',
            'merchant_name' => $merchant['company_name'] ?? '',
            'merchant_mobile' => $merchant['phone'] ?? '',
        ]);
    }

    /**
     *  商户统计
     */
    public function getMerchantStatisticData($where)
    {
        $data =  $this->db('merchant_info')->field("
        count(mer_id) as merchant_num,
        sum(case when status=1 then 1 else 0 end) as merchant_normal_num,
        sum(case when status=0 then 1 else 0 end) as merchant_forbid_num
        ")->where('mer_id', '<>', '')
//                ->where($where)
                ->find() ?? [];

        $money = $this->db('merchant_stock')->removeOption()->where('mer_id','in', function ($queue) use ($where){
            $queue->name('merchant_info')->field('mer_id');
        })->sum('balance');
        return [
            'merchant_num' => $data['merchant_num'] ?? 0,
            'money' => $money ?? 0,
            'merchant_normal_num' => $data['merchant_normal_num'] ?? 0,
            'merchant_forbid_num' => $data['merchant_forbid_num'] ?? 0
        ];

    }
}
